package com.ibiaoke.goods.dao;

import com.google.common.collect.Lists;
import com.ibiaoke.common.base.BaseDao;
import com.ibiaoke.common.base.Page;
import com.ibiaoke.common.consts.CommonConsts;
import com.ibiaoke.common.exception.ServiceException;
import com.ibiaoke.common.utils.AssertUtils;
import com.ibiaoke.goods.consts.GoodsConsts;
import com.ibiaoke.goods.entity.Goods;
import com.ibiaoke.goods.entity.GoodsExample;
import com.ibiaoke.goods.entity.PtGoods;
import com.ibiaoke.goods.entity.ShopPrice;
import com.ibiaoke.goods.mapper.GoodsMapper;
import com.sun.org.apache.bcel.internal.generic.RETURN;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * Created by Administrator on 2017/6/7.
 */
@Repository
public class GoodsDao extends BaseDao<Goods, GoodsExample, Integer, GoodsMapper> {
    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private ShopPriceDao shopPriceDao;

    @Override
    public GoodsMapper getMapper() {
        return goodsMapper;
    }

    /**
     * 商品查询
     *
     * @param goodsId   商品编号
     * @param status    商品上架状态
     * @param goodsName 商品名称
     * @param cateId    商品分类
     * @param shopId
     * @param page      @return
     */
    public List<Goods> listGoods(Integer goodsId, Integer status, String goodsName, Integer cateId, Integer shopId, Page page) {
        GoodsExample example = new GoodsExample();
        GoodsExample.Criteria criteria = example.createCriteria();
        if (goodsId != null) {
            criteria.andGoodsIdEqualTo(goodsId);
        }
        if (status != null) {
            criteria.andStatusEqualTo(status);
        }
        //商品名模糊搜索
        if (StringUtils.isNotEmpty(goodsName)) {
            criteria.andNameLike("%" + goodsName + "%");
        }
        if (cateId != null) {
            criteria.andCateIdEqualTo(cateId);
        }
        if (shopId != null) {
            criteria.andShopIdEqualTo(shopId);
        }
        criteria.andDelStatusEqualTo(CommonConsts.NO);

        page.setTotalCount(goodsMapper.countByExample(example));
        example.setLimitStart(page.limitStart());
        example.setLimitEnd(page.limitEnd());
        example.setOrderByClause("update_time desc");
        return selectByExample(example);
    }

    /**
     * 商品删除
     *
     * @param goodsId
     * @return
     */
    public int deleteGoodsById(Integer goodsId) {
        Goods goods = new Goods();
        goods.setGoodsId(goodsId);
        goods.setDelStatus(1);
        goods.setUpdateTime(new Date());
        if (goodsId == null) {
            throw new ServiceException("商品编号不能为空");
        }
        return updateByPrimaryKeySelective(goods);
    }

    /**
     * 批量删除
     *
     * @param goodsIds
     * @return
     */
    public int batchDeleteGoods(String goodsIds) {
        GoodsExample example = new GoodsExample();
        List<Integer> goodsIdList = new ArrayList<>();
        AssertUtils.notBlank(goodsIds,"商品编号不能为空");
        String[] array = goodsIds.split(",");
        for (int i = 0; i < array.length; i++) {
            goodsIdList.add(Integer.parseInt(array[i]));
        }
        Goods goods = new Goods();
        goods.setDelStatus(CommonConsts.YES);
        goods.setUpdateTime(new Date());
        example.createCriteria().andGoodsIdIn(goodsIdList);
        return updateByExampleSelective(goods, example);
    }


    /**
     * 批量修改商品上下架
     *
     * @param goodsIds
     * @param status
     * @return
     */
    public int batchUpdateGoodsStatus(String goodsIds, Integer status) {
        GoodsExample example = new GoodsExample();
        List<Integer> goodsIdList = new ArrayList<>();
        if (StringUtils.isBlank(goodsIds)) {
            throw new ServiceException("商品编号不能为空");
        }
        if (status == null && status != 1 && status != 2) {
            throw new ServiceException("上下架状态有误");
        }
        String[] array = goodsIds.split(",");
        for (int i = 0; i < array.length; i++) {
            goodsIdList.add(Integer.parseInt(array[i]));
        }
        Goods goods = new Goods();
        goods.setStatus(status);
        goods.setUpdateTime(new Date());
        example.createCriteria().andGoodsIdIn(goodsIdList);
        return updateByExampleSelective(goods, example);
    }

    public int saveGoods(Goods goods) {
        return insertSelective(goods);
    }

    public Goods getGoods(Integer goodsId, Integer shopId) {
        Goods goods = selectByPrimaryKey(goodsId);
        return filterShopPrice(goods, shopId);
    }


    public List<Goods> listByIds(List<Integer> goodsIds, Integer shopId) {
        if (CollectionUtils.isEmpty(goodsIds)) {
            return Lists.newArrayList();
        }
        GoodsExample example = new GoodsExample();
        example.createCriteria().andGoodsIdIn(goodsIds);
        return filterShopPrice(goodsMapper.selectByExample(example), shopId);
    }

    public List<Goods> listGoods(Integer cateId, Integer shopId, Page page) {
        GoodsExample example = new GoodsExample();
        GoodsExample.Criteria criteria = example.createCriteria().andDelStatusEqualTo(CommonConsts.NO)
                .andStatusEqualTo(GoodsConsts.STATUS_ON_SHELF);
        if (cateId != null) {
            criteria.andCateIdEqualTo(cateId);
        }
        page.setTotalCount(goodsMapper.countByExample(example));
        example.setLimitStart(page.limitStart());
        example.setLimitEnd(page.limitEnd());
        example.setOrderByClause("update_time desc");
        return filterShopPrice(goodsMapper.selectByExample(example), shopId);
    }


    public Goods filterShopPrice(Goods goods, Integer shopId) {
        ArrayList<Goods> goodsList = Lists.newArrayList(goods);
        return filterShopPrice(goodsList, shopId).get(0);
    }

    /**
     * 商品店铺价格和库存设置
     *
     * @param goodsList 商品列表
     * @param shopId    店铺id
     */
    public List<Goods> filterShopPrice(List<Goods> goodsList, Integer shopId) {
        if (CollectionUtils.isEmpty(goodsList) || shopId == null) {
            return goodsList;
        }
        //获取所有商品id
        List<Integer> goodsIds = goodsList.stream().map(Goods::getGoodsId).collect(Collectors.toList());
        //获取商品店铺价格
        List<ShopPrice> shopPrices = shopPriceDao.listShopPrice(goodsIds, shopId);
        if (shopPrices == null || CollectionUtils.isEmpty(shopPrices)) {
            for (Goods goods : goodsList) {
                goods.setStockNum(0);
                goods.setShopId(shopId);
            }
            return goodsList;
        }
        //为每个商品设置店铺价格和库存
        goodsList.forEach(goods -> {
            shopPrices.forEach(shopPrice -> {
                //设置店铺价格和库存
                if (Objects.equals(goods.getGoodsId(), shopPrice.getGoodsId())) {
                    goods.setPrice(shopPrice.getPrice());
                    goods.setStockNum(shopPrice.getStockNum());
                }
            });
            goods.setShopId(shopId);
        });
        return goodsList;
    }

    /**
     * 查询出商品，加入拼团活动
     */
    public Goods getGoodByPt(String goodsName) {
        GoodsExample example = new GoodsExample();
        GoodsExample.Criteria criteria = example.createCriteria();
        //商品名模糊搜索
        if (StringUtils.isNotEmpty(goodsName)) {
            criteria.andNameEqualTo(goodsName);
        }
        return getByExample(example);
    }

}
